const formidable = require('formidable')
const moment = require('moment');
const jsonParse = require('../../lib/jsonParse')
const imgServeIp = require('../../config/keys').imgServeIp
const fs = require('fs')


const saveFilePath = function (file, mkFileName) {
    let stream = new Promise((resolve, reject) => {
        const fileNameArr = file.originalFilename.split('.');
        const suffix = fileNameArr[fileNameArr.length - 1];
        const filepath = `${mkFileName}\\${fileNameArr[0]}_${new Date().getTime()}.${suffix}`
        const readStream = fs.createReadStream(file.filepath);
        const writeStream = fs.createWriteStream(filepath);
        readStream.pipe(writeStream);
        readStream.on('end', function () {
            console.log(`已经保存为${filepath}`);
            // fs.unlinkSync(file.filepath);
            // jsonParse.sendResult(res, 200)
            resolve(filepath)
        });
    })
    return stream
}

module.exports = {
    async uploadPic(req, res) {
        const form = formidable({
            multiples: false
        })
        form.parse(req, (err, fields, files) => {
            if (err) {
                res.end(files)
            }
            const file = files.file
            const fileName = moment(new Date()).format('YYYY-MM-DD')
            const mkFileName = `H:\\files\\${fileName}`
            fs.exists(mkFileName, function (exists) {
                if (!exists) {
                    fs.mkdir(mkFileName, (err) => {
                        if (err) {
                            console.log('出错')
                        } else {
                            saveFilePath(file, mkFileName).then(filepath => {
                                jsonParse.sendResult(res, 200, {
                                    path: filepath,
                                    fileName: fileName,
                                    filePath: filepath.replace('H:\\files\\', ''),
                                    doMain: imgServeIp,
                                }, '上传成功')
                            })
                        }
                    })
                } else {
                    saveFilePath(file, mkFileName).then(filepath => {
                        jsonParse.sendResult(res, 200, {
                            path: filepath,
                            fileName: fileName,
                            filePath: filepath.replace('H:\\files\\', ''),
                            doMain: imgServeIp,
                        }, '上传成功')
                    })
                }
            });

        })
    }
}